package com.lancoo.znbkxx.teacher.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.PopupWindow
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.PublishClassListAdapter
import com.lancoo.znbkxx.teacher.adapter.SpacesItemDecoration
import com.lancoo.znbkxx.teacher.model.data.ClassFlag
import com.lancoo.znbkxx.teacher.model.data.TImePickerMin
import com.lancoo.znbkxx.teacher.model.data.TimePickerDate
import com.lancoo.znbkxx.teacher.model.data.TimePickerHour
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import kotlinx.android.synthetic.main.view_publish_class.view.*
import java.text.DateFormatSymbols
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by wealive on 2021/3/9.
 *
 *
 */
@SuppressLint("SetTextI18n")
class PublishPopupWindow(val classList: MutableList<ClassFlag>, val context: Context,
                         val clickListener: View.OnClickListener) :
        PopupWindow(), PublishClassListAdapter.OnCheckedClass {
    lateinit var adapter: PublishClassListAdapter
    private lateinit var dateAdapter: ArrayWheelAdapter<TimePickerDate>
    private lateinit var hourAdapter: ArrayWheelAdapter<TimePickerHour>
    private lateinit var minuteAdapter: ArrayWheelAdapter<TImePickerMin>
    private val dateList = mutableListOf<TimePickerDate>()
    private val hourList = mutableListOf<TimePickerHour>()
    private val minuteList = mutableListOf<TImePickerMin>()
    private var indexDayStart = 0
    private var indexHourStart = 0
    private var indexMinStart = 0
    private var indexDayEnd = 0
    private var indexHourEnd = 0
    private var indexMinEnd = 0

    init {
        val contentView = LayoutInflater.from(context).inflate(R.layout.view_publish_class, null)
        initTimeData()
        with(contentView) {
            tv_select_all.setOnClickListener {
                if (tv_select_all.tag == "selected") {
                    tv_select_all.text = "全选"
                    tv_select_all.tag = "unselected"
                    adapter.selectAll(false)
                } else {
                    tv_select_all.text = "取消全选"
                    tv_select_all.tag = "selected"
                    adapter.selectAll(true)
                }
            }
            val lm = LinearLayoutManager(context).apply { orientation = RecyclerView.HORIZONTAL }
            adapter = PublishClassListAdapter(R.layout.item_class, classList, this@PublishPopupWindow)
            val map = hashMapOf<String, Int>()
            map[SpacesItemDecoration.LEFT_SPACE] = DensityUtils.dp2px(context, 10f)
            val itemDecoration = SpacesItemDecoration(map)
            rv.addItemDecoration(itemDecoration)
            rv.layoutManager = lm
            rv.adapter = adapter
            classList.forEachIndexed { index, classFlag ->
                if (classFlag.CourseClassName == Ext.COURSE_CLASSNAME) {
                    rv.scrollToPosition(index)
                }
            }
            tv_answerTime.text = showCurrentDuration()
            wheel_day.setCyclic(false)
            wheel_hour.setCyclic(false)
            wheel_min.setCyclic(false)
            wheel_day.adapter = dateAdapter
            wheel_hour.adapter = hourAdapter
            wheel_min.adapter = minuteAdapter
            wheel_day.setTextColorCenter(Color.parseColor("#00afff"))
            wheel_hour.setTextColorCenter(Color.parseColor("#00afff"))
            wheel_min.setTextColorCenter(Color.parseColor("#00afff"))
            wheel_day.setTextSize(15f)
            wheel_hour.setTextSize(15f)
            wheel_min.setTextSize(15f)
            wheel_day.wheel_day.setOnItemSelectedListener {
                if (rb_start.isChecked) {
                    indexDayStart = it
                    showTimeText(indexDayStart, indexHourStart, indexMinStart)
                } else {
                    indexDayEnd = it
                    showTimeText(indexDayEnd, indexHourEnd, indexMinEnd)
                }
                tv_answerTime.text = showCurrentDuration()
            }
            wheel_hour.setOnItemSelectedListener {
                if (rb_start.isChecked) {
                    indexHourStart = it
                    showTimeText(indexDayStart, indexHourStart, indexMinStart)
                } else {
                    indexHourEnd = it
                    showTimeText(indexDayEnd, indexHourEnd, indexMinEnd)
                }
                tv_answerTime.text = showCurrentDuration()
            }
            wheel_min.setOnItemSelectedListener {
                if (rb_start.isChecked) {
                    indexMinStart = it
                    showTimeText(indexDayStart, indexHourStart, indexMinStart)
                } else {
                    indexMinEnd = it
                    showTimeText(indexDayEnd, indexHourEnd, indexMinEnd)
                }
                tv_answerTime.text = showCurrentDuration()
            }
            rb_start.text = "开始时间\n${dateList[0].pickerViewText.let {
                it.substring(0, it.lastIndexOf("周"))
            }} ${hourList[indexHourStart].pickerViewText}${minuteList[indexMinStart].pickerViewText}"
            rb_end.text = "结束时间\n${dateList[0].pickerViewText.let {
                it.substring(0, it.lastIndexOf("周"))
            }} ${hourList[indexHourStart].pickerViewText}${minuteList[indexMinStart].pickerViewText}"
            rg_time.setOnCheckedChangeListener { _, checkedId ->
                when (checkedId) {
                    R.id.rb_start -> {
                        wheel_day.currentItem = indexDayStart
                        wheel_hour.currentItem = indexHourStart
                        wheel_min.currentItem = indexMinStart
                    }
                    R.id.rb_end -> {
                        wheel_day.currentItem = indexDayEnd
                        wheel_hour.currentItem = indexHourEnd
                        wheel_min.currentItem = indexMinEnd
                    }
                }
            }
            tv_publish.setOnClickListener(clickListener)
            iv_cancel.setOnClickListener(clickListener)
        }
        this.contentView = contentView
        animationStyle = R.style.PopupWindow
        this.width = WindowManager.LayoutParams.MATCH_PARENT
        this.height = WindowManager.LayoutParams.WRAP_CONTENT
        this.isOutsideTouchable = false
        this.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        this.isFocusable = true
        update()
    }

    private fun initTimeData() {
        for (i in 0..365) {
            val dateTime = Calendar.getInstance()
            dateTime.add(Calendar.DAY_OF_YEAR, i)
            dateTime.set(Calendar.HOUR, 0)
            dateTime.set(Calendar.MINUTE, 0)
            dateTime.set(Calendar.SECOND, 0)
            val datePicker = TimePickerDate(dateTime.get(Calendar.YEAR),
                    dateTime.get(Calendar.MONTH), dateTime.get(Calendar.DAY_OF_MONTH),
                    DateFormatSymbols().shortWeekdays[dateTime.get(
                            Calendar.DAY_OF_WEEK
                    )])
            dateList.add(datePicker)
        }
        dateAdapter = ArrayWheelAdapter(dateList)
        for (i in 0..23) {
            val datePicker = TimePickerHour(i)
            hourList.add(datePicker)
        }
        hourAdapter = ArrayWheelAdapter(hourList)
        for (i in 0..59) {
            val datePicker = TImePickerMin(i)
            minuteList.add(datePicker)
        }
        minuteAdapter = ArrayWheelAdapter(minuteList)
    }

    private fun showTimeText(indexDay: Int, indexHour: Int, indexMin: Int) {
        val timeText = "${dateList[indexDay].pickerViewText.let {
            it.substring(0, it.lastIndexOf("周"))
        }} ${hourList[indexHour].pickerViewText}${minuteList[indexMin].pickerViewText}"
        if (contentView.rb_start.isChecked) {
            contentView.rb_start.text = "开始时间\n${timeText}"
        } else {
            contentView.rb_end.text = "结束时间\n${timeText}"
        }
    }

    fun getStartTime(): String {
        val day = dateList[indexDayStart]
        val hour = hourList[indexHourStart]
        val min = minuteList[indexMinStart]
        val time = Calendar.getInstance()
        time.set(day.year, day.month, day.date, hour.hour, min.min)
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        return sdf.format(time.time)
    }

    fun getEndTime(): String {
        val day = dateList[indexDayEnd]
        val hour = hourList[indexHourEnd]
        val min = minuteList[indexMinEnd]
        val time = Calendar.getInstance()
        time.set(day.year, day.month, day.date, hour.hour, min.min)
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        return sdf.format(time.time)
    }

    private fun showCurrentDuration(): String {
        val sdf = SimpleDateFormat("yyyy.MM.dd HH:mm")
        val dayStart = dateList[indexDayStart]
        val hourStart = hourList[indexHourStart]
        val minStart = minuteList[indexMinStart]
        val timeStart = Calendar.getInstance()
        timeStart.set(dayStart.year, dayStart.month, dayStart.date, hourStart.hour, minStart.min)
        val startStr = sdf.format(timeStart.time)
        val dayEnd = dateList[indexDayEnd]
        val hourEnd = hourList[indexHourEnd]
        val minEnd = minuteList[indexMinEnd]
        timeStart.set(dayEnd.year, dayEnd.month, dayEnd.date, hourEnd.hour, minEnd.min)
        val endStr = sdf.format(timeStart.time)
        return "当前作答期限：$startStr-$endStr"
    }

    override fun checked() {
        with(contentView) {
            if (adapter.isSelectAll()) {
                tv_select_all.text = "取消全选"
                tv_select_all.tag = "selected"
            } else {
                tv_select_all.text = "全选"
                tv_select_all.tag = "unselected"
            }
        }
    }
}